{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "79ae1818",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2023-05-30 10:15:38.627702: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.\n",
      "To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.\n"
     ]
    }
   ],
   "source": [
    "from transformers import BertTokenizer, BertForQuestionAnswering\n",
    "import torch\n",
    "\n",
    "def bert_QA(question, context):\n",
    "    model_name = 'bert-large-uncased'\n",
    "    tokenizer = BertTokenizer.from_pretrained(model_name)\n",
    "    model = BertForQuestionAnswering.from_pretrained(model_name)\n",
    "\n",
    "    # Tokenize the question and context\n",
    "    inputs = tokenizer.encode_plus(question, context, return_tensors='pt', add_special_tokens=True)\n",
    "\n",
    "    # Get the tokenized input IDs, attention mask, and token type IDs\n",
    "    input_ids = inputs['input_ids']\n",
    "    attention_mask = inputs['attention_mask']\n",
    "    token_type_ids = inputs['token_type_ids']\n",
    "\n",
    "    # Perform the question answering inference\n",
    "    outputs = model(input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)\n",
    "\n",
    "    # Get the start and end logits from the model outputs\n",
    "    start_logits = outputs.start_logits\n",
    "    end_logits = outputs.end_logits\n",
    "\n",
    "    # Find the most probable answer span\n",
    "    start_index = torch.argmax(start_logits)\n",
    "    end_index = torch.argmax(end_logits)\n",
    "\n",
    "    # Convert the token indices to actual tokens in the context\n",
    "    answer_tokens = tokenizer.convert_tokens_to_string(tokenizer.convert_ids_to_tokens(input_ids[0][start_index:end_index+1]))\n",
    "\n",
    "    # Return the answer\n",
    "    return answer_tokens\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fb9c66a2",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# Example usage\n",
    "question = \"What is the capital of France?\"\n",
    "context = \"France, officially the French Republic, is a country whose capital is Paris.\"\n",
    "\n",
    "answer = answer_question(question, context)\n",
    "print(\"Answer:\", answer)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
